1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41
| public class Solution { private int count; public int InversePairs(int [] array) { count = 0; if(array != null){ mergeSort(array, 0, array.length - 1); } return count; }
private void mergeSort(int[] a, int start, int end){ if(start >= end) return; int mid = start + (end - start) / 2; mergeSort(a, start, mid); mergeSort(a, mid+1, end); merge(a,start,mid,end); }
private void merge(int[] a, int start, int mid, int end){ int[] temp = new int[end-start+1]; int i = start, j = mid + 1, k = 0; while (i <= mid && j <= end) { if (a[i] <= a[j]) temp[k++] = a[i++]; else { temp[k++] = a[j++]; // ai大于aj,由于归并,所以相反的必定是和所有前面的数字,所以是mid到最左边i中间的数的个数 count = (count + mid - i + 1) % 1000000007; } }
while (i <= mid) temp[k++] = a[i++]; while (j <= end) temp[k++] = a[j++]; for(k=0;k<temp.length;k++){ //将临时数组的数字写回a数组! a[start+k] = temp[k]; } } }
|